/*
TF2 Duel Creator
W]M[D FernFerret
http://www.fernferret.com

This plugin will perform arranged duels intended for use with a map similar to deul_deul2

Thanks To:

	
Versions:
	1.0
	* Initial Release


Todo:
	* Optimise keyvalues usage
	* Save user settings (Done for SM 1.1)
 
Cvarlist (default value):
	sm_dc_enable 1 		Enables/Disables this plugin
	sm_dc_

Admin Commands:
 	sm_start_duel			Starts a duel
 	sm_set_players <1-15>			Sets the number of players per side
	sm_set_special_duel
	
User Commands:
	NONE ATM

*/


#include <sourcemod>
#include <sdktools>
#include <clientprefs>
#include <tf2>

#undef REQUIRE_PLUGIN
#include <adminmenu>

#include "gametype"

#pragma semicolon 1

#define PLUGIN_VERSION "3.1.0"
#define TEAM_SPC 1
#define TEAM_BLU 2
#define TEAM_RED 3



enum sound_types { normal_sounds, admin_sounds, karaoke_sounds, all_sounds };

//new Handle:cvarduelenable = INVALID_HANDLE;
//new Handle:cvarwinnercontinues = INVALID_HANDLE;
//new Handle:cvarnumberofroundstowin = INVALID_HANDLE;
//new Handle:cvarshowsoundmenu = INVALID_HANDLE;
new Handle:listfile = INVALID_HANDLE;
new Handle:hAdminMenu = INVALID_HANDLE;
//			new String:customduellistfile[PLATFORM_MAX_PATH] = "";
//##### Clientprefs #####
//new Handle:dcplayed_cookie = INVALID_HANDLE;
//new Handle:dcwon_cookie = INVALID_HANDLE;
//#######################
new dc_playercount;
new dc_players[MAXPLAYERS+1];
//new da_red_players[MAXPLAYERS+1];
//new da_blu_players[MAXPLAYERS+1];

public Plugin:myinfo = 
{
	name = "TF2 Duel Creator",
	author = "W]M[D FernFerret",
	description = "This Plugin will arrange duels automatically, with several handy options!",
	version = PLUGIN_VERSION,
	url = "http://www.fernferret.com/plugins/"
};

public OnPluginStart(){
	CreateConVar("sm_duel_arranger_version", PLUGIN_VERSION, "Duel Arranger Version", FCVAR_PLUGIN|FCVAR_SPONLY|FCVAR_REPLICATED|FCVAR_NOTIFY|FCVAR_DONTRECORD);
	//cvarduelenable = CreateConVar("sm_da_enable","1","Turns The Duel Arranger On/Off",FCVAR_PLUGIN);
	//cvarwinnercontinues = CreateConVar("sm_da_winnercontinues","1","The winning team will continue to play until they loose.",FCVAR_PLUGIN);
	//cvarnumberofroundstowin = CreateConVar("sm_da_numofroundstowin","2","This works similar to a 2/3, when a team wins X rounds they win");

	//##### Clientprefs #####
	//daplayed_cookie = RegClientCookie("playedlastround", "Did Player play last round", CookieAccess_Protected);
	//dawon_cookie = RegClientCookie("wonlastround", "Was player on winning team?", CookieAccess_Protected);
	RegAdminCmd("sm_dc_generateteam",GenerateTeam,ADMFLAG_GENERIC,"sm_da_generate team <TEAM> <NUMOPLAYERS>");
	RegAdminCmd("sm_dc_test",PrintTest,ADMFLAG_GENERIC,"sm_dc_test");
	//RegAdminCmd("sm_da_setmode",Command_DA_SetMode,ADMFLAG_GENERIC,"sm_da_setmode <0|1> 0: Mode is Both teams random each round; 1: Winning team continues, till round end");
	//RegAdminCmd("sm_da_setrounds",Command_DA_SetRounds,ADMFLAG_GENERIC,"sm_da_setrounds <INTEGER>: Team must win INTEGER rounds to win.");
	//RegAdminCmd("sm_da_enable",Command_DA_Enable,ADMFLAG_GENERIC,"sm_da_enable <0|1> Enable or disable this plugin");

	// Execute the config file
	//AutoExecConfig(true, "sm_duel_arranger");

	if (GetGameType() != tf2){
		ThrowNativeError(0,"This plugin is only for Team Fortress 2 At the Moment.");
	}
	else
	{
		HookEvent("player_death", Event_Kill);
		HookEventEx("player_spawn",PlayerSpawn);
	}
	/* Account for late loading */
	new Handle:topmenu;
	if (LibraryExists("adminmenu") && ((topmenu = GetAdminTopMenu()) != INVALID_HANDLE))
		OnAdminMenuReady(topmenu);
}

public OnLibraryRemoved(const String:name[])
{
	if (StrEqual(name, "adminmenu"))
		hAdminMenu = INVALID_HANDLE;
}
 
public OnAdminMenuReady(Handle:topmenu)
{
	/*************************************************************/
	/* Add a Play Admin Sound option to the SourceMod Admin Menu */
	/*************************************************************/

	/* Block us from being called twice */
	if (topmenu != hAdminMenu){
		/* Save the Handle */
		hAdminMenu = topmenu;
		//new TopMenuObject:server_commands = FindTopMenuCategory(hAdminMenu, ADMINMENU_SERVERCOMMANDS);
		//AddToTopMenu(hAdminMenu, "sm_da_startround", TopMenuObject_Item, Play_Admin_Sound,server_commands, "sm_da_startround", ADMFLAG_GENERIC);
	}
}
public OnMapStart()
{
	dc_playercount = 0;
	for (new i=1; i <= GetMaxClients(); i++)
	{
		dc_players[i] = 0;
		
		if (IsClientInGame(i) && !IsFakeClient(i))
		{
			dc_playercount++;
		}
	}
}
public bool:OnClientConnect(client, String:rejectmsg[], maxlen)
{
	if (!IsFakeClient(client))
	{
		dc_playercount++;
		dc_players[client] = 0;
	}
	return true;
}

public OnClientDisconnect(client)
{
	if (!IsFakeClient(client))
	{
		dc_playercount--;
	}
}
/*public Menu_Select(Handle:menu,MenuAction:action,client,selection)
{
	if(action==MenuAction_Select){
		decl String:SelectionInfo[4];
		decl String:SelectionDispText[PLATFORM_MAX_PATH+1];
		new SelectionStyle;
		if (GetMenuItem(menu,selection,SelectionInfo,sizeof(SelectionInfo),SelectionStyle, SelectionDispText,sizeof(SelectionDispText))){
			KvRewind(listfile);
			KvGotoFirstSubKey(listfile);
			decl String:buffer[PLATFORM_MAX_PATH];
			do{
				KvGetSectionName(listfile, buffer, sizeof(buffer));
				if (strcmp(SelectionDispText,buffer,false) == 0){
					Submit_Sound(client,buffer);
					break;
				}
			} while (KvGotoNextKey(listfile));
		}
	}else if (action == MenuAction_End){
		CloseHandle(menu);
	}
}*/

public ExecuteNewRound()
{
	// count the players on red and blue and team sizes
	new clientCount = GetMaxClients();
	//new redCount = GetTeamClientCount(TEAM_RED);
	//new bluCount = GetTeamClientCount(TEAM_BLU);
	//new spcCount = GetTeamClientCount(TEAM_SPC);
	// Move all players to spec
	for (new i=1; i <= (clientCount); i++)
	{
		if (IsClientConnected(i) && !IsFakeClient(i) && IsClientInGame(i))
		{
			new team = GetClientTeam(i);
			switch (team)
			{
				case TEAM_BLU:
					ChangeClientTeam(i,TEAM_SPC);
				case TEAM_RED:
					ChangeClientTeam(i,TEAM_SPC);
			}
		}
	}
	GenerateTeam(TEAM_BLU,3);
	GenerateTeam(TEAM_RED,3);
}
public Action:PrintTest(client, args)
{
	PrintToChatAll("PrintTest");
	for (new i=0; i <= (GetMaxClients()); i++)
	{
		if (IsClientConnected(i) && !IsFakeClient(i) && IsClientInGame(i))
		{
			new team = GetClientTeam(i);
			PrintToChatAll("Client ID: %s is on team %s",i,team);
		}
	}
	return Plugin_Continue;
}
public Action:GenerateTeam(client, args)
{
	if(args < 3)
	{
		PrintToChatAll("Usage: sm_da_generateteam <TEAM> <PLAYERS>");
	}
	new String: team[5];
	GetCmdArg(1, team, sizeof(team));
	new teamint = StringToInt(team,10);
	new i = 1;
	while(i < GetTeamClientCount(TEAM_SPC))
	{	
		PrintToChatAll("Running While...");
		new playerid = GetRandomInt(0, GetMaxClients());
		if (IsClientConnected(playerid) && !IsFakeClient(playerid) && IsClientInGame(playerid))
		{
			if(GetClientTeam(playerid) != TEAM_SPC)
			{
				PrintToChatAll("This player(%d) has already been assigned to TEAM: %d", playerid ,GetClientTeam(playerid));
			}
			else
			{
				PrintToChatAll("I am assigning Player id %d to Team ID: %d", playerid,teamint);
			}
				//ChangeClientTeam(playerid,teamint);
			i++;
		}

	}
	return Plugin_Continue;
}

public Action:Event_Kill(Handle:event,const String:name[],bool:dontBroadcast)
{
	
}

public Action:PlayerSpawn(Handle:event,const String:name[],bool:dontBroadcast)
{
	
}

public Action:Command_Say(client, args)
{
	if (client <= 0 || !IsClientInGame(client))
	{
		return Plugin_Continue;
	}

	decl String:text[192];
	if (!GetCmdArgString(text, sizeof(text)))
	{
		return Plugin_Continue;
	}
	
	// compensate for quotation marks
	new startidx = 0;
	if(text[strlen(text)-1] == '"')
	{
		text[strlen(text)-1] = '\0';
		startidx = 1;
	}
	
	// loop through word list to see if any of them matches the say text
	new bool:isTriggerWord = false;
	isTriggerWord = (strcmp("!startduel", text[startidx], false) == 0);
	PrintToChatAll("Compared !startduel to %s to result %d", text[startidx], isTriggerWord);
	
	// if player want to trigger scramble, handle it
	if (isTriggerWord)
	{
		GenerateTeam(TEAM_BLU,2);
	}
	
	return Plugin_Continue;
}

public OnMapEnd(){
	if (listfile != INVALID_HANDLE){
		CloseHandle(listfile);
		listfile = INVALID_HANDLE;
	}
}

public OnPluginEnd()
{
	if (listfile != INVALID_HANDLE){
		CloseHandle(listfile);
		listfile = INVALID_HANDLE;
	}
}
